#include "fileuse.h"

fileuse::fileuse()
{
//    fileuse.setFileName("fileDefault.xml");
//    fileName = "fileDefault.xml";
}


//fileuse::fileuse(QString _fileName)
//{
//    fileName = _fileName;
//}

//void fileuse::setFileName(QString _fileName)
//{
//    fileName = _fileName;
//}

QList<ArticleStruct> fileuse::readXML(QString fileName)
{

    QList<ArticleStruct> arsList;
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    }
    int i = 0;
    QXmlStreamReader xml(&file);
    xml.readNext();
    while (!xml.atEnd())
    {
        ArticleStruct ars;
        xml.readNext();
        if (xml.isStartElement() && xml.name() == ("Articles"+QString::number(i)))
        {
            QXmlStreamAttributes attrs = xml.attributes();
            ars.Annotations.append(attrs.value("Annotation").toString());
            ars.ArticleName = attrs.value("Article").toString();
            ars.ArticleUrl = QUrl(attrs.value("URL").toString());
            ars.AuthorNames.append(attrs.value("Author").toString());
            ars.FullText = attrs.value("Text").toString();
            ars.JournalInfo = attrs.value("Info").toString();
            ars.JournalName = attrs.value("Name").toString();
        }

        arsList.append(ars);
                    //++i;
    }
    return arsList;
}

void fileuse::writeXML(QList<ArticleStruct> artStructList, QString fileName)
{
    QFile outputFile(fileName);
    if (!outputFile.open(QIODevice::WriteOnly))// | QIODevice::Append) )
    {

    }
    QXmlStreamWriter stream(&outputFile);
    //QXmlStreamReader
    int i = 0;
    stream.setAutoFormatting(true);
       //  stream.writeStartDocument();
         foreach(ArticleStruct artStruct, artStructList)
         {
         stream.writeStartElement("Articles" + QString::number(i));
         stream.writeAttribute("URL", artStruct.ArticleUrl.toString());
         stream.writeAttribute("Article", artStruct.ArticleName);
         stream.writeAttribute("Name", artStruct.JournalName);
         stream.writeAttribute("Author", artStruct.AuthorNames.at(0));
         stream.writeAttribute("Annotation", artStruct.Annotations.at(0));
         stream.writeAttribute("Text", artStruct.FullText);
         stream.writeAttribute("Info", artStruct.JournalInfo);
         //stream.writeTextElement("title", "Qt Home");
         stream.writeEndElement(); // Articles
         //++i;
         }
       //  stream.writeEndDocument();
    outputFile.close();
}
